﻿using Currency.Infra.Repository.Entities;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics.CodeAnalysis;

namespace Currency.Infra.EntityFramework
{
    public class EfCoreDbContext : DbContext
    {
        private readonly IEntityInfo _entityInfo;

        public EfCoreDbContext([NotNull] DbContextOptions options, [NotNull] IEntityInfo entityInfo)
            : base(options)
        {
            _entityInfo = entityInfo;

            //关闭DbContext默认事务
            Database.AutoTransactionsEnabled = false;
            //关闭查询跟踪
            //ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        /// <summary>
        /// 重写实体映射
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasCharSet("utf8mb4 ");//设置Mysql表

            var (Assembly, Types) = _entityInfo.GetEntitiesInfo();

            foreach (var entityType in Types)
            {
                modelBuilder.Entity(entityType);
            }

            modelBuilder.ApplyConfigurationsFromAssembly(Assembly);

            base.OnModelCreating(modelBuilder);
        }
    }
}
